package com.winton.common;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;

import javax.swing.table.TableModel;

public class PassWord {
	public String enCode(String str) {
	    try {
	        // 生成一个MD5加密计算摘要
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        // 计算md5函数
	        md.update(str.getBytes());
	        // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
	        // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
	        return new BigInteger(1, md.digest()).toString(16);
	    } catch (Exception e) {
	        return null;
	    }
	}
	
	
	
	public String EnString(String value)
    {
		String mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        if (value == null || value.isEmpty())
        {
            return "";
        }

        byte[] buff;
        StringBuilder sb = new StringBuilder();
		try {
			buff = value.getBytes("GBK");
	        int j, k, m;
	        int len = mstr.length();
	        java.util.Random r = new java.util.Random();

	        for (int i = 0; i < buff.length; i++)
	        {
	            j = (byte)r.nextInt(6);
	            buff[i] = (byte)((int)buff[i] ^ j);
	            int temp = (int)buff[i];
	            temp = temp + 256;
	            k = temp % len;
	            m = temp / len;
	            m = m * 8 + j;
	            System.out.println(buff[i]+"===="+k + "=====" + m);
	            sb.append(mstr.substring(k, k+1) + mstr.substring(m, m+1));
	            System.out.println(sb.toString());
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}

        return sb.toString();
    }
	
	public String DeString(String value)
    {
		String mstr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        if (value == null || value.isEmpty())
        {
            return "";
        }

        int j, k, m, n = 0;
        int len = mstr.length();
        byte[] valueBuff = value.getBytes();
        byte[] buff = new byte[value.length() / 2];

        for (int i = 0; i < value.length(); i += 2)
        {
            k = mstr.indexOf(valueBuff[i]);
            m = mstr.indexOf(valueBuff[i + 1]);
            j = m / 8;
            m = m - j * 8;
            buff[n] = (byte)(j * len + k);
            buff[n] = (byte)((int)buff[n] ^ m);
            buff[n] -= 256;
            n++;
        }
        String result = "";
		try {
			result = new String(buff, "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}

        System.out.println(result);
        return result;
    }
	
}
